#!/usr/bin/python
# coding:utf-8
__author__ = 'good'
__createday__ = '2015-01-15'

from flask import current_app, session, Blueprint
import time
import datetime
from threading import Thread
from flask.ext.mail import Message
from flask_themes2 import render_theme_template
from .decorators import send_async_email
import pkgutil
import importlib


def register_blueprints(app, package_name, package_path):
    """Register all Blueprint instances on the specified Flask application found
    in all modules for the specified package.
    :param app: the Flask application
    :param package_name: the package name
    :param package_path: the package path
    """
    rv = []
    for _, name, _ in pkgutil.iter_modules(package_path):
        m = importlib.import_module('%s.%s' % (package_name, name))
        for item in dir(m):
            item = getattr(m, item)
            if isinstance(item, Blueprint):
                prefix = '/' + item.name
                app.register_blueprint(item, prefix=prefix)
            rv.append(item)
    return rv


#: 生成随机密码
def make_random_passwd(l=None):
    import random

    app = current_app._get_current_object()
    if l is None:
        l = app.config['RANDOM_PASSWORD_LENGTH']
    basicstring = '''23456789abcdefghjkmnpqrtuvwxyzABCDEFGHJKMNPQRTUVWXYZ!@#$%^&*()_+=-[]{}/'''
    pwd = ''.join(random.sample(basicstring, l))
    return pwd


#: 主题渲染
def blog_render(template, **context):
    theme = session.get('theme', current_app.config.get('DEFAULT_THEME', 'color'))
    return render_theme_template(theme, template, **context)


#: UTC时间转本地时间
def utc2local(utc_st):
    now_stamp = time.time()
    local_time = datetime.datetime.fromtimestamp(now_stamp)
    utc_time = datetime.datetime.utcfromtimestamp(now_stamp)
    offset = local_time - utc_time
    local_st = utc_st + offset
    return local_st


#: 本地转UTC时间
def local2utc(local_st):
    time_struct = time.mktime(local_st.timetuple())
    utc_st = datetime.datetime.utcfromtimestamp(time_struct)
    return utc_st
